package com.mmlc.meimei.lichengkongjian.classify;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;

import com.androidnetframe.BaseParentActivity;
import com.androidnetframe.httputil.BaseRequestFilterLayer;
import com.androidnetframe.httputil.EntryPageName;
import com.androidnetframe.responsejavabean.RequestError;
import com.mmlc.inter.InterActivity;
import com.mmlc.meimei.lichengkongjian.R;
import com.mmlc.meimei.lichengkongjian.customview.CusSimplePagerTitleView;
import com.mmlc.meimei.lichengkongjian.customview.MyTriangularPagerIndicator;
import com.mmlc.network.filter.CategoryListRequestFilter;
import com.mmlc.network.responsebean.MqFastBuyCategoryResponseBean;
import com.mmlc.utils.ToastUtils;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/12/5.
 */
public class MeiQiFastBuyActivity extends InterActivity {


    private List<String> mTitles ;
    private PagerAdapter adapter ;


    @InjectView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    @InjectView(R.id.view_pager)
    ViewPager mViewPager;
    @InjectView(R.id.rootView)
    ViewGroup rootView;

    List<Fragment> fragments;
    @Override
    protected int initContentView() {
        return R.layout.activity_meiqifastbuy;
    }
    @Override
    protected void initView() {
        ButterKnife.inject(this);
        mTitles = new ArrayList<>();
        adapter = new PagerAdapter(getSupportFragmentManager());
        fragments = new ArrayList<>();
        initCateId();
    }
    String cateId;
    private void initMagicIndicator() {
        magicIndicator.setBackgroundColor(Color.WHITE);
        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setScrollPivotX(0.5f);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mTitles == null ? 0 : mTitles.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                CusSimplePagerTitleView simplePagerTitleView = new CusSimplePagerTitleView(context);
                simplePagerTitleView.setText(mTitles.get(index));
                simplePagerTitleView.setNormalColor(Color.GRAY);
                simplePagerTitleView.setSelectedColor(Color.BLACK);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                MyTriangularPagerIndicator indicator = new MyTriangularPagerIndicator(context);
                indicator.setLineColor(Color.BLACK);
                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        mViewPager.setOffscreenPageLimit(5);
        ViewPagerHelper.bind(magicIndicator, mViewPager);
        cateId = getIntent().getStringExtra("cate_id");

    }

    public void changeFragment(String cate_id){
        int k = 0;
        for (int i = 0; i < data.getCate_list().size(); i++) {
            if(cate_id.equals(data.getCate_list().get(i).getId()+"")){
                k = i;
                break;
            }
        }
        mViewPager.setCurrentItem(k+1);
    }
    public class PagerAdapter extends FragmentPagerAdapter {


        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return mTitles.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles.get(position);
        }
    }

    @OnClick(R.id.iv_back)
    public void back(){
        int item = mViewPager.getCurrentItem();
        if(item == 0) {
            finish();
        }else{
            mViewPager.setCurrentItem(0);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            int item = mViewPager.getCurrentItem();
            if(item == 0) {
                finish();
            }else{
                mViewPager.setCurrentItem(0);
            }
        }
        return true;
    }



    final Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what) {
                case 1:
                    MqFastBuyCategoryResponseBean.DataBean.H5Bean h5 = data.getH5();
                    MeiQiWebFragment mqWeb = new MeiQiWebFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("url",h5.getUrl());
                    mqWeb.setArguments(bundle);
                    fragments.add(mqWeb);
                    for (int i = 0; i < data.getCate_list().size(); i++) {
                        MQFastBuyFragment mq = new MQFastBuyFragment();
                        Bundle bun = new Bundle();
                        bun.putString("id",data.getCate_list().get(i).getId());
                        mq.setArguments(bun);
                        fragments.add(mq);
                    }

                    mViewPager.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                    if(!TextUtils.isEmpty(cateId)){
                        changeFragment(cateId);
                    }
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(handler!=null){
            handler.removeCallbacksAndMessages(null);
        }
    }
    MqFastBuyCategoryResponseBean.DataBean data;
    private void initCateId() {

        int zg_cate_id;
        if(EntryPageName.globalRequestBean==null){
            zg_cate_id = 2000;
        }else if(null == EntryPageName.globalRequestBean.getData()){
            zg_cate_id = 2000;

        }else {
            zg_cate_id = EntryPageName.globalRequestBean.getData().getZg_cate_id();
        }
        if(TextUtils.isEmpty(zg_cate_id+"")){
            zg_cate_id = 2000;
        }
        CategoryListRequestFilter filter = new CategoryListRequestFilter((BaseParentActivity) activity);
        filter.requestBean.pid = zg_cate_id+"";
        filter.offerErrorParams(rootView);
        filter.isTransparence = true;
        filter.sendRequest(new BaseRequestFilterLayer.AccessResultFromFilter<MqFastBuyCategoryResponseBean>() {
            @Override
            public void onSuccess(MqFastBuyCategoryResponseBean result) {
                if(result!=null) {
                    data = result.getData();
                    String name = data.getH5().getName();
                    mTitles.add(name);
                    for (int i = 0; i < data.getCate_list().size(); i++) {
                        mTitles.add(data.getCate_list().get(i).getName());

                    }
                    initMagicIndicator();
                    magicIndicator.setVisibility(View.VISIBLE);
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }else{
                    ToastUtils.showToast("数据类型错误");
                }
            }

            @Override
            public void onFailed(View errorLayout, RequestError serverError, int failedType) {

            }
        });

    }



}
